import FS from 'fs-extra'
import path from 'path'
import { IFileDirStat, getExt } from 'recursive-readdir-files'
export * from './tsconfig'

/**置空文件夹*/
export const clearOutDir = (output: string) => {
  FS.emptyDirSync(output)
}

export function outputLog(filename: string, output: string) {
  output = path.relative(process.cwd(), output)
  const extname = path.extname(output).replace('.', '')

  const name = `\x1b[35m ${filename}\x1b[0m`
  if (/\.map$/.test(output)) {
    console.log(
      `♻️ ${name}\x1b[36;1m MAP\x1b[0m ┈┈▶ \x1b[32;1m${output}\x1b[0m`,
    )
  } else if (/d.ts$/.test(output)) {
    console.log(
      `♻️ ${name}\x1b[34;1m DTS\x1b[0m ┈┈▶ \x1b[32;1m${output}\x1b[0m`,
    )
  } else if (extname == 'css') {
    console.log(
      `♻️ ${name}\x1b[35;1m CSS \x1b[0m┈┈▶ \x1b[32;1m${output}\x1b[0m`,
    )
  } else if (extname == 'js') {
    console.log(
      `♻️ ${name}\x1b[33;1m JS \x1b[0m ┈┈▶ \x1b[32;1m${output}\x1b[0m`,
    )
  } else {
    console.log(
      `♻️ ${name}\x1b[37;1m ${(
        extname || '***'
      ).toLocaleUpperCase()} \x1b[0m ┈┈▶ \x1b[32;1m${output}\x1b[0m`,
    )
  }
}

export const getOneFieldWriteFile = (files?: string[]) => {
  let newFiles: IFileDirStat[] = []
  if (files) {
    files.forEach((filepath) => {
      const stat = FS.statSync(filepath)
      if (stat.isFile) {
        newFiles.push({
          ext: getExt(filepath),
          name: path.basename(filepath),
          path: filepath,
        })
      }
    })
  }
  return newFiles
}

export const getEnterFieldMap = (
  fileNames: string[],
  outFileNames: string[],
  entry: string,
  outDir: string,
) => {
  const newMap = new Map()
  const newFileNames = fileNames
    .map((filename) => {
      const ext = path.extname(filename).replace(/^\./, '')
      const rgx = new RegExp(`\.${ext}$`)
      return {
        ext: ext,
        name: filename.replace(rgx, ''),
        path: filename,
      }
    })
    .filter((item) => ['ts', 'tsx'].includes(item.ext))
  outFileNames.forEach((filename) => {
    if ('js' === getExt(filename) || /\.d\.ts/.test(filename)) {
      const newFilenamePath = filename
        .replace(/\.(js|d\.ts)/, '')
        .replace(outDir, entry)
      const item = newFileNames.find((it) => it.name === newFilenamePath)
      const toFilename = (item && item.path) || filename
      newMap.set(filename, toFilename)
    } else {
      newMap.set(filename, filename.replace(outDir, entry))
    }
  })
  return newMap
}
